// 实现随机推荐功能
$.ajax({
  type: 'get',
  url: '/posts/random',
  success: function (response) {
    let randomTpl = `
      {{each data}}
        <li>
          <a href="/detail.html?id={{$value._id}}">
            <p class="title">{{$value.title}}</p>
            <p class="reading">阅读({{$value.meta.views}})</p>
            <div class="pic">
              <img src="{{$value.thumbnail}}" alt="">
            </div>
          </a>
        </li>
      {{/each}}
      `;
    let html = template.render(randomTpl, {
      data: response
    });
    $('#randomBox').html(html);
  }
})

// 实现最新评论功能
$.ajax({
  type: 'get',
  url: '/comments/lasted',
  success: function (response) {
    let commentTpl = `
    {{each data}}
    <li>
      <a href="javascript:;">
        <div class="avatar">
          <img src="{{$value.author.avatar}}" alt="">
        </div>
        <div class="txt">
          <p>
          <span>{{$value.author.nickName}}</span>{{$imports.dateFormat($value.createAt)}}说:
          </p>
          <p>{{$value.content}}</p>
        </div>
      </a>
    </li>
    {{/each}}
    `;
    let html = template.render(commentTpl, {
      data: response
    });
    $('#commentBox').html(html);
  }
});

// 实现导航栏nav的展示
$.ajax({
  type: 'get',
  url: '/categories',
  success: function (response) {
    let navTpl = `
    {{each data}}
    <li><a href="list.html?categoryId={{$value._id}}"><i class="fa {{$value.className}}"></i>{{$value.title}}</a></li>
    {{/each}}
    `;
    let html = template.render(navTpl, {
      data: response
    });
    $('#navBox').html(html);
    $('#topnavBox').html(html);
  }
})

// 点击搜索时，跳转到搜索页面
$('.search form').on('submit', function () {
  let keys = $(this).find('.keys').val();
  location.href = 'search.html?key=' + keys;
  return false;
})

//处理日期格式
function dateFormat(date) {
  date = new Date(date);
  return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
}

// 从地址栏中获得查询参数
function getUrlParams(name) {
  let paramAry = location.search.substr(1).split('&');
  for (let i = 0; i < paramAry.length; i++) {
    let tmp = paramAry[i].split('=');
    if (tmp[0] == name) return tmp[1];
  }
  return null;
}